//
//  YDAOptionController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/21.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDAOptionController.h"
#import "YDAOptionalNoDataView.h"
#import "YDAOptionalStockModel.h"
#import "YDAOptionalCell.h"
#import "YDAOptionalTableHeaderView.h"
#import "YDHomeMarketView.h"
#import "YDHomeMarketModel.h"

#import "YDAOptionEditingController.h"
#import "YDASearchController.h"
#import "YDALoginController.h"
#pragma 跳转到详情
#import "YDVerticalStockBuyController.h"
#import "YDStockMarketDetailController.h"


@interface YDAOptionController ()<SYAOptionalNoDataViewDelegate , SYHomeMarketViewDelegate , UITableViewDelegate , UITableViewDataSource>

//无数据View
@property (nonatomic , weak) YDAOptionalNoDataView *noDataView;

//引导登录页面
@property (nonatomic, weak)SYGuideLoginView *guideLoginView;

//tableView
@property (nonatomic , weak) UITableView *tableView;

@property (nonatomic , strong) NSMutableArray *modelArray;

@property (nonatomic , strong) NSMutableArray *marketModelArray;


@property (nonatomic , weak) YDHomeMarketView *marketView;

//定时器
@property (nonatomic , strong) NSTimer *optionalTimer;
//是不是正在刷新
@property (nonatomic , assign) BOOL optionalTimerIsRunning;

//大盘数据
@property (nonatomic , strong) NSTimer *optionalMTimer;
//大盘数据是不是正在刷新
@property (nonatomic , assign) BOOL optionalMTimerIsRunning;

@end

@implementation YDAOptionController

-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(NSMutableArray *)marketModelArray
{
    if (_marketModelArray == nil) {
        _marketModelArray = [NSMutableArray array];
    }
    return _marketModelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    self.title = @"自选";
    
    
    [self setUpNavButton];
    [self tableView];
    [self setUpDataManger];
    [self addNotification];
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if ([SYUserInformation sharedInstance].isLogin) {
        [self loadData];
    }else{
        [self removeTableView];
        [self removeNoDataView];
        self.navigationItem.leftBarButtonItem = nil;
        [self guideLoginView];
    }
    
    [self viewOpenTimer];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self removeNoDataView];
    [self removeGuideView];
    [self viewStopTimer];
}


#pragma 开始通知
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewOpenTimer) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationWillTerminateNotification object:nil];
}

-(void)viewOpenTimer
{
    if (self.optionalTimer && self.optionalMTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"开启定时器")
    self.optionalTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadOptionalStockData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.optionalTimer forMode:NSRunLoopCommonModes];
    
    self.optionalMTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadMarketStockData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.optionalMTimer forMode:NSRunLoopCommonModes];
}
-(void)viewStopTimer
{
    if (!self.optionalTimer && !self.optionalMTimer)return;
    
    DDLog(@"关闭定时器")
    [self.optionalTimer invalidate];
    self.optionalTimer = nil;
    [self.optionalMTimer invalidate];
    self.optionalMTimer = nil;
}


#pragma 移除tableView
-(void)removeTableView
{
    if (_tableView) {
        [self.tableView removeFromSuperview];
        self.tableView = nil;
        self.marketView = nil;
    }
}
#pragma 添加tableView
-(void)addTableView
{
    [self tableView];
    [self setUpDataManger];
}
#pragma 移除无数据view
-(void)removeNoDataView
{
    if (_noDataView) {
        [self.noDataView removeFromSuperview];
        self.noDataView = nil;
    }
}
- (void)removeGuideView
{
    if (_guideLoginView) {
        [_guideLoginView removeFromSuperview];
        _guideLoginView = nil;
    }
}
#pragma 添加导航栏按钮
-(void)setUpNavButton
{
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"mjbtwosousuo"] hightImage:[UIImage imageNamed:@"mjbtwosousuo"] addTarget:self action:@selector(rightItemButtonClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}
//进入搜索界面
-(void)rightItemButtonClick:(UIButton *)button
{
    
    [self popToSearchViewWithSearchString:@""];
    
}

-(void)popToSearchViewWithSearchString:(NSString *)searchString
{
    YDASearchController *vc = [[YDASearchController alloc] init];
    vc.searchString = searchString;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
}



- (void)addLeftNavigationBarItem
{
    UIBarButtonItem *leftItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"zx-bianji"] hightImage:[UIImage imageNamed:@"zx-bianji"] addTarget:self action:@selector(leftItemBtnClick:)];
    self.navigationItem.leftBarButtonItem = leftItemBtn;
}

-(void)leftItemBtnClick:(UIButton *)button
{
    if (self.modelArray.count) {//进入编辑界面
        YDAOptionEditingController *vc = [[YDAOptionEditingController alloc] init];
        vc.optionalStockArray = self.modelArray;
        vc.hidesBottomBarWhenPushed = YES;
        YDABaseNavigationController *nav = [[YDABaseNavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        
        
    }else{//无数据
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"暂无股票收藏"
                                                      isExistNav:YES];
    }
}

-(void)setUpDataManger
{
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    header.lastUpdatedTimeLabel.hidden = NO;//是否隐藏最后一次刷新时间
    header.stateLabel.hidden = NO;//是否隐藏刷新状
    self.tableView.mj_header = header;
    
}

-(YDHomeMarketView *)marketView
{
    if (_marketView == nil) {
        CGFloat marketViewH;
        if (isPhoneX) {
            marketViewH = rateX812(85);
        }else{
            marketViewH = rate750(85);
        }
        YDHomeMarketView *marketView = [YDHomeMarketView homeMarketViewMarketModelArray:self.marketModelArray];
        marketView.frame = CGRectMake(0, 0, LKScreenW, marketViewH);
        self.tableView.tableHeaderView = marketView;
        marketView.delegate = self;
        _marketView = marketView;
        
    }
    return _marketView;
}

#pragma SYHomeMarketViewDelegate
-(void)homeMarketView:(YDHomeMarketView *)homeMarketView didSelectItemAtIndex:(NSInteger)index
{
#pragma 跳转到大盘详情
    if (!self.marketModelArray.count)return;
    
    for (YDHomeMarketModel *model in self.marketModelArray) {
        model.isSelected = NO;
    }
    
    YDHomeMarketModel *model = self.marketModelArray[index];
    model.isSelected = YES;
    YDStockMarketDetailController *vc = [[YDStockMarketDetailController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.isNormal = NO;
    vc.marketModelArray = self.marketModelArray;
    vc.stockName = model.name;
    vc.stockCode = model.code;
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
    
}
-(void)loadData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetOptionalStockList WithSuccessBlock:^(NSDictionary *resultDict) {
        if (_tableView) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.modelArray removeAllObjects];
            
            self.modelArray = [YDAOptionalStockModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
            [self removeGuideView];
            [self removeNoDataView];
            
            if (self.modelArray.count) {
                [self addTableView];
                [self addLeftNavigationBarItem];
                [self.tableView reloadData];
                [self loadMarketData];
            }else{
                [self removeTableView];
                self.navigationItem.leftBarButtonItem = nil;
                [self noDataView];
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage
                                                                text:@"信息加载出错，请重试~"
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        if (_tableView) {
            [self.tableView.mj_header endRefreshing];
        }
        [self noDataView];
    }];
    
}
/*******加载大盘数据**********/
-(void)loadMarketData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetMarketData WithSuccessBlock:^(NSDictionary *resultDict) {
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.marketModelArray removeAllObjects];
            self.marketModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self marketView];
            
            self.marketView.marketModelArray = self.marketModelArray;
            
            [self.tableView reloadData];
            
        }else{
        }
    } failBlock:^(NSError *error) {
    }];
    
}
#pragma tableView
-(UITableView *)tableView
{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        _tableView = tableView;
    }
    return _tableView;
}

#pragma UITableViewDelegate , UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(44) : rate750(44);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(56) : rate750(56);;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDAOptionalTableHeaderView *headerView = [YDAOptionalTableHeaderView headerViewWithTableView:tableView];
    return headerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAOptionalCell *cell = [YDAOptionalCell cellWithTableView:tableView];
    YDAOptionalStockModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
#pragma 跳转到详情
    YDAOptionalStockModel *model = self.modelArray[indexPath.row];
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isNormal = NO;
    vc.isActivity = NO;
    vc.isPopToRootC = NO;
    vc.stockCode = model.code;
    vc.stockName = model.name;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

#pragma 无数据
-(YDAOptionalNoDataView *)noDataView
{
    if (_noDataView == nil) {
        YDAOptionalNoDataView *noDataView = [[YDAOptionalNoDataView alloc] init];
        noDataView.frame = self.view.bounds;
        [self.view addSubview:noDataView];
        noDataView.delegate = self;
        _noDataView = noDataView;
    }
    return _noDataView;
}

#pragma SYAOptionalNoDataViewDelegate
-(void)optionalNoDataView:(YDAOptionalNoDataView *)dataView buttonStyle:(SYAOptionalNoDataViewButtonStyle)style searchString:(NSString *)searchString
{
    
    if (style == SYAOptionalNoDataViewStyleDefault) {
        [self popToSearchViewWithSearchString:searchString];
    }else{
        [self popToSearchViewWithSearchString:searchString];
    }
    
}

-(SYGuideLoginView *)guideLoginView
{
    if (_guideLoginView ==  nil) {
        if (![SYUserInformation sharedInstance].isLogin) {
            //没有登录贴引导登录展位图
            
            SYGuideLoginView *guideLoginView = [[SYGuideLoginView alloc] init];
            [self.view addSubview:guideLoginView];
            [guideLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self.view);
                make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
            }];
            LK(weakSelf)
            [guideLoginView setClickBlock:^(BOOL isClick) {
                //点击去登陆
                
                
                YDALoginController *loginVC = [[YDALoginController alloc] init];
                loginVC.loginStyle = Login_Present;
                YDABaseNavigationController *baseNav = [[YDABaseNavigationController alloc] initWithRootViewController:loginVC];
                [weakSelf presentViewController:baseNav animated:YES completion:nil];
            }];
            
            _guideLoginView = guideLoginView;
        }
    }
    return _guideLoginView;
}


#pragma 定时加载自选信息
-(void)timeLoadOptionalStockData
{
    if (self.optionalTimerIsRunning || !self.modelArray.count)return;
    self.optionalTimerIsRunning = YES;
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetOptionalStockList WithSuccessBlock:^(NSDictionary *resultDict) {
        
        self.optionalTimerIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.modelArray removeAllObjects];
            
            self.modelArray = [YDAOptionalStockModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self.tableView reloadData];
            
            
        }else{
        }
    } failBlock:^(NSError *error) {
        
        self.optionalTimerIsRunning = NO;
    }];
}
-(void)timeLoadMarketStockData
{
    if (self.optionalMTimerIsRunning || !self.modelArray.count)return;
    self.optionalMTimerIsRunning = YES;
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetMarketData WithSuccessBlock:^(NSDictionary *resultDict) {
        self.optionalMTimerIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.marketModelArray removeAllObjects];
            self.marketModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self marketView];
            self.marketView.marketModelArray = self.marketModelArray;
            [self.tableView reloadData];

        }else{
        }
    } failBlock:^(NSError *error) {
        self.optionalMTimerIsRunning = NO;
    }];
    
    
    
}


@end
